package com.hugoo.core.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Hugoo.Chan
 */
public class Prop {

    public static Prop load(String... path) {
        if (path == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (String x : path) {
            if (x != null) {
                sb.append(x).append(",");
            }
        }
        return new Prop(sb.toString());
    }
    private String path;

    private Prop(String path) {
        if (path.contains("WEB-INF/classes")) {
            path = path.replace("WEB-INF/classes/", "");
        }
        this.path = path;
    }

    public boolean to(Map m) {
        Properties p;
        FileInputStream in = null;
        String[] px = path.split(",");
        for (String pz : px) {
            if (TL.isEmpty(pz)) {
                continue;
            }
            log.info("正在加载【" + pz + "】......");
            try {
                p = new Properties();
                in = new FileInputStream(Prop.class.getResource(pz).getPath());
                p.load(in);//属性文件将该流加入的可被读取的属性中
                //******添加数据集************************
                m.putAll(p);
                //******释放数据集************************
                p.clear();
            } catch (FileNotFoundException ex) {
                log.error(path + "文件未找到!", ex);
            } catch (IOException ex) {
                log.error(path + "文件读取错误!", ex);
            } catch (Exception e) {
                log.error("加载属性文件【" + path + "】出现未知错误!", e);
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception ex) {
                    log.warn("关闭属性文件出现异常", ex);
                }
            }
        }
        return true;
    }
    private final static Log log = LogFactory.getLog(Prop.class);
}
